package com.example.everying.task;

import com.example.everying.model.entity.content.ActivityComment;
import com.example.everying.service.content.ActivityCommentService;
import com.example.everying.service.content.ActivityThumbService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @program: everything
 * @description: 定时器任务类
 * @author: zw
 * @create: 2025-05-22 11:50
 **/

@Component
@Slf4j
public class SyncCommentsToDatabaseTask {
    private static final String COMMENT_DATA_KEY = "comment:%s";
    private static final String PENDING_SYNC_KEY = "pending_sync_comments";
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ActivityCommentService commentService;
    @Autowired
    private ActivityThumbService activityThumbService;

    /**
     * 定时同步redis中"评论"到数据库
     */
    @Scheduled(fixedRate = 1000) // 每3秒执行一次
    public void syncCommentsToDatabase() {
        try {
            //获取待同步的评论id集合
            Set<Object> pendingIds = redisTemplate.opsForSet().members(PENDING_SYNC_KEY);
            if (pendingIds == null || pendingIds.isEmpty()) {
                return;
            }
            //从redis中批量获取评论数据
            List<ActivityComment> comments = new ArrayList<>();
            for (Object id : pendingIds) {
                ActivityComment comment = getCommentFromRedis((String) id);
                if (comment != null) {
                    comments.add(comment);
                }
            }
            //批量保存到数据库兵一处已处理的id
            if (!comments.isEmpty()) {
                commentService.saveBatch(comments);
                redisTemplate.opsForSet().remove(PENDING_SYNC_KEY, pendingIds.toArray());
            }
        } catch (Exception e) {
            // 记录异常信息，避免影响后续定时任务执行
            System.err.println("评论同步任务执行失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 从redis中获取评论的数据
     * @param id
     * @return
     */
    private ActivityComment getCommentFromRedis(String id) {
        try {
            String dataKey = String.format(COMMENT_DATA_KEY, id);
            return (ActivityComment) redisTemplate.opsForValue().get(dataKey);
        } catch (Exception e) {
            System.err.println("从Redis获取评论失败，ID: " + id + ", 错误: " + e.getMessage());
            return null;
        }
    }


    /**
     * 每3m执行一次，将Redis中的"点赞"数据同步到数据库
     */
    @Scheduled(fixedRate = 1000)
    public void syncLikesToDatabase() {
        try {
            activityThumbService.syncLikesToDatabase();
        } catch (Exception e) {
            log.error("Error in scheduled likes sync task", e);
        }
    }
}
